from socket import *
from multiprocessing import Process
import re

HTML_DIR = "./html"
class ServerSocket(object):
    def __init__(self):
        self.serSocket = socket(AF_INET, SOCK_STREAM)
        self.serSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    def run(self,clientSocket):
        recvData = clientSocket.recv(1024)
        print("recvdata = ", recvData)
        recvLines = recvData.splitlines()
        requestStartLine = recvLines[0]

        fileName = re.match(r"\w+\s+(/[^ ]*)", requestStartLine.decode("utf-8")).group(1)
        if fileName == "/":
            fileName = "/index3.html"
        try:
            file = open(HTML_DIR + fileName, "rb")
            fileData = file.read()
            file.close()
        except IOError:
            responseStartLine = "HTTP/1.1 404 NOT FOUND\r\n"
            responseServer = "Server:myServer\r\n"
            responseBody = "file si not found"
        else:
            responseStartLine = "HTTP/1.1 200 OK\r\n"
            responseServer = "Server:myServer \r\n"
            responseBody = fileData.decode("utf-8")

        response = responseStartLine + responseServer + "\r\n" + responseBody
        clientSocket.send(bytes(response, 'gb2312'))
        clientSocket.close()
    def start(self):
        self.serSocket.listen(12)
        while True:
            clientSocket, clientAddr = self.serSocket.accept()
            print(str(clientAddr), "连上了")
            p1 = Process(target=self.run, args=(clientSocket,))
            p1.start()
            clientSocket.close()
    def bind(self,port):
        self.serSocket.bind(("", port))
def main():
    sersocket = ServerSocket()
    sersocket.bind(7000)
    sersocket.start()
if __name__ == "__main__":
    main()

